package com.errol.generic.http.impl;

import com.renjia.service.http.HttpBuilder;
import com.renjia.service.http.HttpLogger;
import com.renjia.service.http.HttpResult;
import com.renjia.service.http.HttpService;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author zhang xiao bin
 * @version v1.0
 * @date 2020/10/10
 * @since v
 **/
@Service
public class HttpUrlConnectionServiceImpl implements HttpService {
    private final ThreadPoolExecutor executor;
    private final HttpLogger httpLogger;

    public HttpUrlConnectionServiceImpl(HttpLogger httpLogger) {
        this.httpLogger = httpLogger;
        executor = new ThreadPoolExecutor(3, 10, 30, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(100));
        executor.allowCoreThreadTimeOut(true);
    }

    @PreDestroy
    public void destroy() {
        executor.shutdown();
    }

    @Override
    public HttpBuilder builder(String url) {
        return HttpBuilder.builder(new HttpUrlConnectionComponent(), httpLogger, url);
    }

    @Override
    public <T> HttpResult<T> execute(HttpBuilder.HttpPlan<T> httpPlan) {
        return httpPlan.execute();
    }

    @Override
    public <T> Future<HttpResult<T>> submit(HttpBuilder.HttpPlan<T> httpPlan) {
        return executor.submit(() -> execute(httpPlan));
    }
}
